<template>
  <el-drawer :title="title" :visible.sync="visible" :size="size" :before-close="handleClose" custom-class="form-drawer"
    append-to-body :destroy-on-close="true">
    <div class="drawer-content">
      <question-form v-model="formData" ref="formRef" @success="handleSaveSuccess" />

      <div class="drawer-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit" loading-text="保存中...">确 定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import api from '@/common/api';
import QuestionForm from './QuestionForm.vue'

export default {
  name: 'QuestionFormDrawer',
  components: {
    QuestionForm
  },
  props: {
    size: {
      type: String,
      default: '800'
    },
  },
  data() {
    return {
      visible: false,
      loading: false,
      formData: {}
    }
  },
  computed: {
    title() {
      return this.formData?.id ? '编辑习题' : '新增习题'
    },
  },
  methods: {
    async open(data) {
      this.visible = true

      const obj = Object.assign({}, data)
      if (obj.id) {
        try {
          this.loading = true
          const res = await api.admin_getQuestionDetail(obj.id)
          this.formData = Object.assign({}, obj, res.data.data)
        } catch (error) {
          this.$message.error('获取习题详情失败')
        } finally {
          this.loading = false
        }
      } else {
        this.formData = obj
      }
    },
    handleClose() {
      this.formData = {}
      this.visible = false
    },
    async handleSubmit() {
      this.loading = true
      this.$refs.formRef.doSubmit(()=>{this.loading = false})
    },
    handleSaveSuccess() {
      this.$emit('success')
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.form-drawer {
  .drawer-content {
    padding: 20px;
    padding-bottom: 60px;
    overflow-y: auto;
  }

  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 20px;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    text-align: right;

    .el-button {
      margin-left: 8px;
    }
  }
}

:deep .el-form-item {
  margin-bottom: 12px;
}
</style>